<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');

class File_cabinets extends MY_Controller {
	
	
	var $path;// 文件路径
	var $name;//文件名
	var $result;//对文件操作后的结果
	var $global_address;
	public function __construct(){
		parent::__construct();
		$this->load->helper('directory');
		$this->load->helper('file');
		$this->user_name = $this->session->userdata('user_name');
		$this->global_address = FCPATH.'attach\\files\\'.$this->user_name.'\\';
		$init_add = mb_convert_encoding($this->global_address,'GBK','UTF-8');
		if(!is_dir($init_add)){   
			@mkdir($init_add,0777);   
		}
	}
    

	var $id = 1;
	function get_tree($data,$t = 'folder',$childKey = 'children'){
		$tree = array();
		global $id;
		if($t == 'folder'){
			foreach ($data as $rk => $rv){
				if(is_array($rv)){
					$arr2['id'] = ++$id;
					$arr2['text'] = mb_convert_encoding($rk,'UTF-8','GBK');
					$arr2['state'] = 'open';
					$arr2['iconCls'] = 'icon-folder';
					$arr2[$childKey] = $this->get_tree($rv,$t,$childKey);
					
					if(!empty($arr2[$childKey])){
						$arr2['state'] = 'closed';
					}

					$tree[] = $arr2;
				}
			}
		}else if($t == 'file'){
			foreach ($data as $rk => $rv){
				if(is_array($rv)){
					$arr['id'] = ++$id;
					$arr['filename'] = mb_convert_encoding($rv['filename'],'UTF-8','GBK');
					$arr['filesize'] = $rv['filesize'];
					$arr['filectime'] = $rv['filectime'];
					$tree[] = $arr;
				}
			}
		}
		return $tree;
	}
	
	//文件夹列表
	function _folder_list_post(){
		$dir = mb_convert_encoding($this->global_address,'GBK','UTF-8');
		$map = directory_map($dir);	//取得指定目录树的数组
		$dir_tree = $this->get_tree($map,'folder');				//返回TREE能够识别的数组
		echo json_encode($dir_tree); 					//打印为JSON格式
	}

	//读取指定路径的文件函数
	function directory_map_detailed($source_dir){
		if ($fp = @opendir($source_dir)){
			$filedata	= array();

			$source_dir	= rtrim($source_dir, DIRECTORY_SEPARATOR).DIRECTORY_SEPARATOR;
	
			while (FALSE !== ($file = readdir($fp))){
				
				if ( ! trim($file, '.') OR ($file[0] == '.')){
					continue;
				}
	
				if (@!is_dir($source_dir.$file)){
					$file_dir = $source_dir.$file;
					//$filesize = (filesize($file_dir) != 0)?filesize($file_dir):'0';
					$files = array('filename'=>$file,'filectime'=>date("Y-m-d H:i:s",filectime($file_dir)),'filesize'=>byte_format(filesize($file_dir), 2));
					$filedata[] = $files;
				}
			}
			closedir($fp);
			return $filedata;
		}
	
		return FALSE;
	}
	

	
	//新建文件夹
	function _folder_new_post(){
		$path_str = $this->input->post('path_str');
		$path_str = $this->global_address.trim($path_str);		
		$path_str = mb_convert_encoding($path_str,'GBK','UTF-8');		
		if(is_dir($path_str)){
			echo 2;
		}else{
			echo @mkdir($path_str, 0777); 
		}
	}
	
	//删除文件夹
	function _folder_del_post(){
		$path_str = $this->input->post('path_str');
		$path_str = $this->global_address.$path_str;
		$path_str = mb_convert_encoding($path_str,'GBK','UTF-8');		
		if(!is_dir($path_str)){
			echo 2;
		}else{
			if(delete_files($path_str,TRUE)){
				echo rmdir($path_str);
			}			
		}
	}
	
	//重命名文件夹
	function _folder_renaming_post(){
		$path_str = $this->input->post('path_str');	
		$path_str = trim($path_str);//删除首位空格
		$new_name = $this->input->post('new_name');
		$str = substr($path_str,0,-1);//删除最后一个斜杠
		
		$n = strrpos($str,'/');
		if($n != 0){
			$str = substr($path_str,0,$n);
			$str = $str.'/'.$new_name.'/';
		}else{
			$str = $new_name.'/';
		}

		$path_str = mb_convert_encoding($this->global_address.$path_str,'GBK','UTF-8');
		$str = mb_convert_encoding($this->global_address.$str,'GBK','UTF-8');
		echo rename($path_str,$str);	
	}
	
	//复制目录下的所有文件及文件夹
	//参数说明：   
	// $source:源目录名   
	// $destination:目的目录名
	function recurse_copy($source, $destination){
		if(!is_dir($source)){   
			echo("Error:the $source is not a direction!");   
			return 0;   
		}   
		if(!is_dir($destination)){   
			@mkdir($destination,0777);   
		}   
		$handle=dir($source); 
		while($entry=$handle->read()) {   
			if(($entry!=".")&&($entry!="..")){   
				if(is_dir($source."/".$entry)){   
					$this->recurse_copy($source."/".$entry,$destination."/".$entry);   
				}else{ 
					$entry_old = $entry;
					while(file_exists($destination.$entry)){ 								//循环判断旧文件名在新位置是否有重名文件，如果有则重命名为副本
						$entry = mb_convert_encoding($entry,'UTF-8','GBK'); //对处理后的文件名进行转码
						$suffix = end(explode(".",$entry)); 								//提取文件名后缀
						$new_name = substr($entry,0,strrpos($entry, '.'));				//提取文件名不带后缀
						$entry = $new_name.' - 副本.'.$suffix; 							//拼接成新文件名
						$entry = mb_convert_encoding($entry,'GBK','UTF-8'); //对处理后的文件名进行转码
					};
					//$entry_new = mb_convert_encoding($entry_new,'GBK','UTF-8'); //对处理后的文件名进行转码
					copy($source."/".$entry_old,$destination."/".$entry);   


				}   
			}   
		}   
		return 1;   
	} 
	
	//复制文件夹的粘贴
	function _folder_copy_post(){
		$v = true;//最终状态变量
		$data = $this->input->post();	 											//获取POST参数
		$path_old = $this->global_address.$data['path_old']; 						//拼接旧文件夹路径		
		$path_new = $this->global_address.$data['path_new']; 						//拼接新文件夹路径
		
		$path_old = mb_convert_encoding($path_old,'GBK','UTF-8');
		$path_new = mb_convert_encoding($path_new,'GBK','UTF-8');
		
		echo $this->recurse_copy($path_old,$path_new);
	}
	
	//文件夹移动
	function folder_move($source,$target){
		/*检查要移动的额目录是否存在*/
		if(!file_exists($source))return false;
		/*检查移动后的存储目录是否存在*/
		if(!file_exists($target))@mkdir($target);
		/*打开目录并获取文件*/
		$dir        =@opendir($source);
		$files        =array();    //用来存储目录下的文件
		$dirs        =array();    //用来存储目录下的子目录
		if(false!=$dir){
			while($item    =readdir($dir)){
				$itemPath    =$source.'/'.$item;
				if($item!='.'&&$item!='..'){
					if(filetype($itemPath)=='file'){
						$files[]    =$item;
					}elseif(filetype($itemPath)=='dir'){
						$dirs[]        =$item;
					}
				}
			}
			@closedir($dir);
		}
		/*复制文件到目标地址*/
		foreach($files as $file){
			@copy($source.'/'.$file,$target.'/'.$file);    //拷贝文件到目标地址
			@unlink($source.'/'.$file);                    //删除原始文件
		}
		 
		/*递归处理子目录*/
		if(sizeof($dirs)>0){
			foreach($dirs  as $childDir){
				$this->move_folder_files($source.'/'.$childDir,$target.'/'.$childDir);
			}
		}
		//删除当前目录
		@rmdir($source);
		return true;
	}
	
	//剪切文件夹的粘贴
	function _folder_cur_post(){
		$v = true;//最终状态变量
		$data = $this->input->post();	 											//获取POST参数
		$path_old = $this->global_address.$data['path_old']; 						//拼接旧文件夹路径		
		$path_new = $this->global_address.$data['path_new']; 						//拼接新文件夹路径
		
		$path_old_s = substr($path_old,0,-1);
		$new_name = substr($path_old_s,strrpos($path_old_s, '/'));
		$path_old = mb_convert_encoding($path_old,'GBK','UTF-8');
		$path_new = mb_convert_encoding($path_new.$new_name,'GBK','UTF-8');
		
		if(!is_dir($path_new)){   
			@mkdir($path_new,0777);   
		} 
		
		
		echo $this->move_folder_files($path_old,$path_new);
	}

	//文件列表视图
	function files_list(){
		$this->load->view('file_cabinets/files_list');		
	}
	
	//文件列表数据
	function _files_list_post(){
		//$dir = $this->uri->uri_string();									//获取URL数据
		$dir = $this->input->post('folder_str',TRUE);
		//$dir = urldecode($dir);												//RUL解码
		//$dir = substr_replace($dir,"",0,32); 									//去掉控制器和方法名
		$dir = iconv( "UTF-8", "GBK//IGNORE" , $this->global_address.$dir);						//字符串编码从UTF-8转GBK
		$map = $this->directory_map_detailed($dir);	//取得指定路径的文件信息数组
		$dir_tree = ($map != false)?$this->get_tree($map,'file'):array();	//返回datagrid能够识别的数据
		echo json_encode($dir_tree); 										//打印为JSON格式

	}

	//文件删除
	function _files_del_post(){
		$v = true;
		$data = $this->input->post();	
		$path = $this->global_address.$data['getpath'];
		foreach($data['getname'] as $name){
			$str = $path.$name;

			$str = mb_convert_encoding($str,'GBK','UTF-8');
			
			if(file_exists($str)) {
				$result=unlink($str);
				if(!$result)$v=false;
			}else{
				$v = false;	
			}
		}
		echo $v;
	}
	
	//文件重命名
	function _files_renaming_post(){
		$data = $this->input->post(NULL,TRUE);	
		$path_str = trim($data['path_str']);//删除文件名首尾空格
		$old_name = iconv( "UTF-8", "GBK//IGNORE" , $this->global_address.$path_str.$data['old_name']);
		$new_name = iconv( "UTF-8", "GBK//IGNORE" , $this->global_address.$path_str.$data['new_name']);
		echo rename($old_name,$new_name);	
	}
	
	//复制文件的粘贴
	function _files_copy_post(){
		$v = true;//最终状态变量
		$data = $this->input->post();	 											//获取POST参数
		$path_old = $this->global_address.$data['path_old']; 						//拼接旧文件夹路径
		$path_new = $this->global_address.$data['path_new']; 						//拼接新文件夹路径
		foreach($data['getname'] as $name){											//循环执行所选则的文件
			$path_old_file = iconv( "UTF-8", "GBK//IGNORE" , $path_old.$name); 	//拼接带文件名的旧详细路径
			$path_new_file = iconv( "UTF-8", "GBK//IGNORE" , $path_new.$name); 	//拼接带文件名的新详细路径
			if(file_exists($path_old_file)){										//判断旧文件路径是否存在
				while(file_exists($path_new_file)){ 								//循环判断旧文件名在新位置是否有重名文件，如果有则重命名为副本
					$suffix = end(explode(".",$name)); 								//提取文件名后缀
					$new_name = substr($name,0,strrpos($name, '.'));				//提取文件名不带后缀
					$name = $new_name.' - 副本.'.$suffix; 							//拼接成新文件名
					$path_new_file = iconv( "UTF-8", "GBK//IGNORE" , $path_new.$name); //对处理后的文件名进行转码
				};
				$result = copy($path_old_file,$path_new_file);						//执行复制操作
				if(!$result)$v=false;
				
			}else{
				$v = false;	
			}
		}
		echo $v;
	}
	
	//文件剪切的粘贴
	function _files_cut_post(){
		$v = true;//最终状态变量
		$data = $this->input->post();	 												//获取POST参数
		$path_old = $this->global_address.$data['path_old']; 							//拼接旧文件夹路径
		$path_new = $this->global_address.$data['path_new']; 							//拼接新文件夹路径
		foreach($data['getname'] as $name){												//循环执行所选则的文件
			$path_old_file = iconv( "UTF-8", "GBK//IGNORE" , $path_old.$name); 			//拼接带文件名的旧详细路径
			$path_new_file = iconv( "UTF-8", "GBK//IGNORE" , $path_new.$name); 			//拼接带文件名的新详细路径
			if($path_old_file != $path_new_file){
				if(file_exists($path_old_file)){										//判断旧文件路径是否存在
					while(file_exists($path_new_file)){ 								//循环判断旧文件名在新位置是否有重名文件，如果有则重命名为副本
						$suffix = end(explode(".",$name)); 								//提取文件名后缀
						$new_name = substr($name,0,strrpos($name, '.'));				//提取文件名不带后缀
						$name = $new_name.' - 副本.'.$suffix; 							//拼接成新文件名
						$path_new_file = iconv( "UTF-8", "GBK//IGNORE" , $path_new.$name); //对处理后的文件名进行转码
					};
					$result = rename($path_old_file,$path_new_file);						//执行复制操作
					if(!$result)$v=false;
					
				}else{
					$v = false;	
				}
			}
		}
		echo $v;
	}
	
	//新建文件
	function _files_new_post(){
		//$data['str'] = $this->input->post('str',TRUE);
		//$str = $this->uri->uri_string();
		//$data['str'] = urldecode(substr($str,24));
		//echo $str;
		$this->load->view('file_cabinets/files_new');		
	}
	
	
	//个人文件柜模块上传文件到文件模块的指定文件夹
	//上传文件
	function _upload_post(){
		$data = $this->input->post(NULL,TRUE);
		$attdir = empty($data['attdir'])?'':$data['attdir'];
		$upload_path = $this->global_address.$attdir; // 相对于根
		$upload_path = iconv("UTF-8","GBK//IGNORE",$upload_path);
		if(!is_dir($upload_path)) mkdir($upload_path, 0755); 		
		
		$verifyToken = md5('unique_salt' . $data['timestamp']);
		if (!empty($_FILES) && $data['token'] == $verifyToken) {	
			$config['upload_path']	 =	$upload_path;
			//$config['allowed_types'] =	reduce_multiples(implode('|',$this->attachment_type), "|", TRUE);//数组转字符串以竖线分割并去首尾和重复的竖线
			$config['allowed_types'] =	'*';
			$config['overwrite'] =	true;
			//$config['rand_prefix']	 =	random_string('nozero',9);
			$this->load->library('upload',$config);
			if($this->upload->do_upload('Filedata')){
				$arr = $this->upload->data();				
				$data = array("flag"=>true,"str"=>'');
			}else{
				$data = array("flag"=>false,"str"=>$this->upload->display_errors());
			}
			echo json_encode($data); 
		}
	}
	/*
	function _files_m_post(){
		$select_dir = $this->input->post('attdir');
		//$select_dir = (@$_POST['attdir'] == '')?'':@$_POST['attdir'].'/';
		$targetFolder = $this->global_address.$select_dir; // 相对于根

		$verifyToken = md5('unique_salt' . $_POST['timestamp']);
		if (!empty($_FILES) && $_POST['token'] == $verifyToken) {
			$tempFile = $_FILES['Filedata']['tmp_name'];

			//$targetPath = FCPATH . $targetFolder;
			//$filename = str_replace(array('(', ')'), array('（','）'), $_FILES['Filedata']['name']);
			
			$filename = $_FILES['Filedata']['name'];
			//$filename = iconv("UTF-8","GBK",$_FILES['Filedata']['name']);

			
			
			$targetFile = mb_convert_encoding(rtrim($targetFolder,'/') . '/' .$filename,"GBK","UTF-8");
			
			while(file_exists($targetFile)){ 								//循环判断旧文件名在新位置是否有重名文件，如果有则重命名为副本
				$suffix = end(explode(".",$filename)); 								//提取文件名后缀
				$new_name = substr($filename,0,strrpos($filename, '.'));				//提取文件名不带后缀
				$filename = $new_name.' - 副本.'.$suffix; 							//拼接成新文件名
				$targetFile = mb_convert_encoding($targetFolder.$filename,'GBK','UTF-8'); //对处理后的文件名进行转码
			};

			// 验证文件类型
			$fileTypes = array('jpg','jpeg','gif','png','psd','bmp','doc','docx','xls','xlsx','ppt','pptx','mp3','mp4','avi','mpg','mpeg','wma','wav','rm','rmvb','swf','flv','rar','zip','7z','exe'); // 文件扩展名
			$fileParts = pathinfo($filename);//以数组的形式返回文件路径的信息。
			
			if (in_array(strtolower($fileParts['extension']),$fileTypes)) {
				move_uploaded_file($tempFile,$targetFile);
				echo true;
			} else {
				echo '无效的文件类型.';
			}
			
		}

	}
	*/
	/*个人文件柜模块上传后，确定前删除文件函数*/
	function _files_del_up_post(){
		$json = $this->input->post('data');
		$m = $this->input->post('m');
		$filearr = json_decode($json,true);

		//$filename = str_replace(array('(', ')'), array('（','）'), $filearr['name']);//处理文件名中的特殊字符
		
		//$daterand = explode('_',$filearr['daterand']);//把日期、随机数组合进行拆分
		$select_dir = (@$m == '')?'':@$m.'/';
		
		$file = $this->global_address.$select_dir.$filearr['name'];//拼接文件地址
		
		$file = iconv( "UTF-8", "GBK//IGNORE" , $file);//转换为GBK，防止中文文件名出现乱码
		
		$status = !unlink($file)?false:true;//三目判断删除状态
		
		$status = array("status"=>$status);
		echo json_encode($status);//返回JSON格式数据
	}
	
	//判断文件是否存在
	function _file_exist_post(){
		$file_name = $this->input->post('file_name', TRUE);
		$status = file_exists($this->global_address.iconv( "UTF-8", "GBK//IGNORE" , $file_name));
		echo json_encode(array("status"=>$status)); 
	}
	
	/*附件下载*/
	function _file_down_post(){
		$data = $this->input->post(NULL, TRUE);
		$folder_str = iconv( "UTF-8", "GBK//IGNORE" , $data['folder_str']);
		$file_name = iconv( "UTF-8", "GBK//IGNORE" , $data['file_name']);
		$file_dir = $this->global_address.$folder_str.iconv( "UTF-8", "GBK//IGNORE" , $file_name);

		$data = file_get_contents($file_dir); // 读文件内容
		force_download($file_name, $data);
	}
	
	//其他模块调用个人文件柜
	function select_filebox_out(){
		$data['m'] = $this->uri->segment(3, 0);
		$this->load->view('file_cabinets/select_filebox_out',$data);	
	}
	
	//从文件柜选择附件
	function _select_files_out_post(){
		$data = $this->input->post();	 											//获取POST参数
		$getpath = $this->global_address.$data['getpath']; 						//拼接旧文件夹路径
		
		$datedir = date('ym');

		$path_new = FCPATH.'attach/'.$data['m'].'/'.$datedir.'/'; // 相对于根
		
		foreach($data['getname'] as $name){											//循环执行所选则的文件
			$randfilename = mt_rand(000000000,999999999);
			$path_old_file = mb_convert_encoding($getpath.$name,'GBK','UTF-8'); 	//拼接带文件名的旧详细路径
			$path_new_file = mb_convert_encoding($path_new.$randfilename.'.'.$name,'GBK','UTF-8'); 	//拼接带文件名的新详细路径

			$result = copy($path_old_file,$path_new_file);						//执行复制操作
			if(!$result)$v=false;
			$filesize = filesize($path_new_file);
			$arrstr[] = array('daterand'=>$datedir.'_'.$randfilename,'size'=>$filesize);
		}
		echo json_encode($arrstr);//返回JSON格式数据

	}
	
	//其他模块调用个人文件柜
	function select_filebox_in(){
		$data['m'] = $this->uri->segment(3, 0);
		$data['id'] = $this->uri->segment(4, 0);
		$data['filename'] = $this->uri->segment(5, 0);
		$this->load->view('file_cabinets/select_filebox_in',$data);	
	}
	
	//其他模块附件转存到个人文件柜
	function _select_files_in_post(){
		$data = $this->input->post(NULL,TRUE);	 										//获取POST参数
		$att_id = explode('_',$data['id']);		//分解为数组
		$filename = urldecode($data['filename']);
		$find = array("&#40;","&#41;");
		$replace = array("(",")");
		$filename = str_replace($find,$replace,$filename);
		$path_old = FCPATH.'attach/'.$data['m'].'/'.reset($att_id).'/'.end($att_id).'.'.$filename;  
		$getpath = $this->global_address.$data['getpath']; 

		$path_old = mb_convert_encoding($path_old,'GBK','UTF-8'); 	//拼接带文件名的旧详细路径
		$path_new = mb_convert_encoding($getpath.$filename,'GBK','UTF-8'); 	//拼接带文件名的新详细路径

		if(file_exists($path_old)){
			while(file_exists($path_new)){ 								//循环判断旧文件名在新位置是否有重名文件，如果有则重命名为副本
				$suffix = end(explode(".",$filename)); 								//提取文件名后缀
				$new_name = substr($filename,0,strrpos($filename, '.'));				//提取文件名不带后缀
				$filename = $new_name.' - 副本.'.$suffix; 							//拼接成新文件名
				$path_new = mb_convert_encoding($getpath.$filename,'GBK','UTF-8'); //对处理后的文件名进行转码
			};
			$str = copy($path_old,$path_new);						//执行复制操作	

		}else{
			$str = false;
		}
		$this->rejsonsuccess($str,'源文件没有找到或拷贝错误！');
	}
}
?>
